import { ExportEngine, ExportType, ExportData, ExportOptions, ExportProgress } from './types'

/**
 * 文本导出引擎
 * 生成纯文本和Markdown格式的分镜脚本
 */
export class TextExportEngine implements ExportEngine {
  type = ExportType.TEXT
  
  /**
   * 生成文本文件
   */
  async generate(
    data: ExportData,
    options: ExportOptions,
    onProgress?: (progress: ExportProgress) => void
  ): Promise<Blob> {
    try {
      onProgress?.({
        stage: 'preparing',
        progress: 0,
        message: '准备生成文本文件...'
      })
      
      let content = ''
      
      if (options.type === ExportType.MARKDOWN) {
        content = this.generateMarkdown(data, options, onProgress)
      } else {
        content = this.generatePlainText(data, options, onProgress)
      }
      
      onProgress?.({
        stage: 'completed',
        progress: 100,
        message: '文本文件生成完成'
      })
      
      const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
      return blob
      
    } catch (error) {
      onProgress?.({
        stage: 'error',
        progress: 0,
        message: '生成文本文件时发生错误',
        error: error instanceof Error ? error.message : String(error)
      })
      throw error
    }
  }
  
  /**
   * 生成Markdown格式
   */
  private generateMarkdown(
    data: ExportData,
    options: ExportOptions,
    onProgress?: (progress: ExportProgress) => void
  ): string {
    let content = ''
    const { projectInfo, scenes, statistics } = data
    
    onProgress?.({
      stage: 'processing',
      progress: 10,
      message: '生成项目信息...'
    })
    
    // 项目信息
    content += `# ${projectInfo.title}\n\n`
    
    if (projectInfo.description) {
      content += `**项目描述**: ${projectInfo.description}\n\n`
    }
    
    content += `**创建时间**: ${projectInfo.createdAt.toLocaleDateString()}\n`
    content += `**总场景数**: ${projectInfo.totalScenes}\n`
    content += `**总时长**: ${projectInfo.totalDuration.toFixed(1)}秒\n\n`
    
    content += '---\n\n'
    
    onProgress?.({
      stage: 'processing',
      progress: 30,
      message: '生成场景内容...'
    })
    
    // 场景内容
    const scenesToExport = options.includeAll
      ? scenes
      : scenes.filter(scene => options.selectedSceneIds?.includes(scene.id))
    
    scenesToExport.forEach((scene, index) => {
      const progress = 30 + (index / scenesToExport.length) * 50
      onProgress?.({
        stage: 'processing',
        progress,
        message: `处理场景: ${scene.title}`
      })
      
      content += `## 场景 ${scene.order + 1}: ${scene.title}\n\n`
      
      // 基本信息表格
      content += '| 项目 | 信息 |\n'
      content += '|------|------|\n'
      content += `| 时长 | ${scene.duration}秒 |\n`
      content += `| 镜头类型 | ${scene.shotType} |\n`
      content += `| 拍摄角度 | ${scene.cameraAngle} |\n`
      
      if (scene.cameraMovement && scene.cameraMovement !== '静止') {
        content += `| 镜头运动 | ${scene.cameraMovement} |\n`
      }
      
      content += `| 拍摄地点 | ${scene.location} |\n`
      content += `| 场景类型 | ${scene.locationType} |\n`
      content += `| 光线条件 | ${scene.lighting} |\n`
      content += `| 优先级 | ${scene.priority} |\n`
      content += `| 复杂度 | ${scene.complexity} |\n`
      
      if (scene.characters.length > 0) {
        content += `| 出场人物 | ${scene.characters.join(', ')} |\n`
      }
      
      if (scene.props.length > 0) {
        content += `| 相关道具 | ${scene.props.join(', ')} |\n`
      }
      
      content += '\n'
      
      // 场景描述
      if (scene.description) {
        content += '### 场景描述\n\n'
        content += `${scene.description}\n\n`
      }
      
      // 制作备注
      if (scene.notes && scene.notes !== scene.description) {
        content += '### 制作备注\n\n'
        content += `${scene.notes}\n\n`
      }
      
      content += '---\n\n'
    })
    
    // 统计信息
    if (options.includeStatistics) {
      onProgress?.({
        stage: 'processing',
        progress: 85,
        message: '生成统计信息...'
      })
      
      content += '## 项目统计信息\n\n'
      
      content += '### 基础统计\n\n'
      content += `- 总场景数: ${statistics.totalScenes}\n`
      content += `- 总时长: ${statistics.totalDuration.toFixed(1)}秒 (${(statistics.totalDuration / 60).toFixed(1)}分钟)\n`
      content += `- 平均时长: ${statistics.averageDuration.toFixed(1)}秒\n`
      
      if (statistics.longestScene) {
        content += `- 最长场景: ${statistics.longestScene.title} (${statistics.longestScene.duration}秒)\n`
      }
      
      if (statistics.shortestScene) {
        content += `- 最短场景: ${statistics.shortestScene.title} (${statistics.shortestScene.duration}秒)\n`
      }
      
      content += '\n'
      
      content += '### 镜头类型分布\n\n'
      Object.entries(statistics.scenesByType).forEach(([type, count]) => {
        content += `- ${type}: ${count}个\n`
      })
      
      content += '\n'
      
      content += '### 场景要素\n\n'
      content += `- 拍摄地点数量: ${statistics.locationCount}\n`
      content += `- 出场人物数量: ${statistics.characterCount}\n`
    }
    
    return content
  }
  
  /**
   * 生成纯文本格式
   */
  private generatePlainText(
    data: ExportData,
    options: ExportOptions,
    onProgress?: (progress: ExportProgress) => void
  ): string {
    let content = ''
    const { projectInfo, scenes, statistics } = data
    
    onProgress?.({
      stage: 'processing',
      progress: 10,
      message: '生成项目信息...'
    })
    
    // 项目信息
    content += `${projectInfo.title}\n`
    content += '='.repeat(projectInfo.title.length) + '\n\n'
    
    if (projectInfo.description) {
      content += `项目描述: ${projectInfo.description}\n`
    }
    
    content += `创建时间: ${projectInfo.createdAt.toLocaleDateString()}\n`
    content += `总场景数: ${projectInfo.totalScenes}\n`
    content += `总时长: ${projectInfo.totalDuration.toFixed(1)}秒\n\n`
    
    content += '-'.repeat(50) + '\n\n'
    
    onProgress?.({
      stage: 'processing',
      progress: 30,
      message: '生成场景内容...'
    })
    
    // 场景内容
    const scenesToExport = options.includeAll
      ? scenes
      : scenes.filter(scene => options.selectedSceneIds?.includes(scene.id))
    
    scenesToExport.forEach((scene, index) => {
      const progress = 30 + (index / scenesToExport.length) * 50
      onProgress?.({
        stage: 'processing',
        progress,
        message: `处理场景: ${scene.title}`
      })
      
      content += `场景 ${scene.order + 1}: ${scene.title}\n`
      content += '-'.repeat(30) + '\n'
      
      content += `时长: ${scene.duration}秒\n`
      content += `镜头类型: ${scene.shotType}\n`
      content += `拍摄角度: ${scene.cameraAngle}\n`
      
      if (scene.cameraMovement && scene.cameraMovement !== '静止') {
        content += `镜头运动: ${scene.cameraMovement}\n`
      }
      
      content += `拍摄地点: ${scene.location}\n`
      content += `场景类型: ${scene.locationType}\n`
      content += `光线条件: ${scene.lighting}\n`
      content += `优先级: ${scene.priority}\n`
      content += `复杂度: ${scene.complexity}\n`
      
      if (scene.characters.length > 0) {
        content += `出场人物: ${scene.characters.join(', ')}\n`
      }
      
      if (scene.props.length > 0) {
        content += `相关道具: ${scene.props.join(', ')}\n`
      }
      
      if (scene.description) {
        content += `\n场景描述:\n${scene.description}\n`
      }
      
      if (scene.notes && scene.notes !== scene.description) {
        content += `\n制作备注:\n${scene.notes}\n`
      }
      
      content += '\n' + '-'.repeat(50) + '\n\n'
    })
    
    // 统计信息
    if (options.includeStatistics) {
      onProgress?.({
        stage: 'processing',
        progress: 85,
        message: '生成统计信息...'
      })
      
      content += '项目统计信息\n'
      content += '='.repeat(12) + '\n\n'
      
      content += '基础统计:\n'
      content += `  总场景数: ${statistics.totalScenes}\n`
      content += `  总时长: ${statistics.totalDuration.toFixed(1)}秒 (${(statistics.totalDuration / 60).toFixed(1)}分钟)\n`
      content += `  平均时长: ${statistics.averageDuration.toFixed(1)}秒\n`
      
      if (statistics.longestScene) {
        content += `  最长场景: ${statistics.longestScene.title} (${statistics.longestScene.duration}秒)\n`
      }
      
      if (statistics.shortestScene) {
        content += `  最短场景: ${statistics.shortestScene.title} (${statistics.shortestScene.duration}秒)\n`
      }
      
      content += '\n镜头类型分布:\n'
      Object.entries(statistics.scenesByType).forEach(([type, count]) => {
        content += `  ${type}: ${count}个\n`
      })
      
      content += '\n场景要素:\n'
      content += `  拍摄地点数量: ${statistics.locationCount}\n`
      content += `  出场人物数量: ${statistics.characterCount}\n`
    }
    
    return content
  }
  
  /**
   * 获取支持的导出选项
   */
  getSupportedOptions(): Partial<ExportOptions> {
    return {
      includeStatistics: true,
      includeTechnicalParams: true,
      includeNotes: true
    }
  }
}

/**
 * Markdown导出引擎
 */
export class MarkdownExportEngine extends TextExportEngine {
  type = ExportType.MARKDOWN
  
  async generate(
    data: ExportData,
    options: ExportOptions,
    onProgress?: (progress: ExportProgress) => void
  ): Promise<Blob> {
    const markdownOptions = { ...options, type: ExportType.MARKDOWN }
    return super.generate(data, markdownOptions, onProgress)
  }
}